package com.isaacwaller.digg;

import static com.isaacwaller.digg.DiggInterface.reportError;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

// Lists stories
public class ListStories extends ListActivity {
	static final String TAG = "DiggListStories";
	
	enum Mode {
		POPULAR("popular",R.string.popular),
		UPCOMING("upcoming",R.string.upcoming),
		TOP("top",R.string.top),
		HOT("hot",R.string.hot);
		
		int nameid;
		String pathAppend;
		Mode(String pa,int id) {pathAppend=pa;nameid=id; }
	}
	
	
	Mode currentMode = Mode.TOP;
	
	public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        MenuInflater inflater = new MenuInflater(this);
        inflater.inflate(R.menu.categorystories, menu);
        return result;
    }
	
	public boolean onPrepareOptionsMenu(final Menu menu) {       
	    super.onPrepareOptionsMenu(menu); 
	    menu.findItem(R.id.popular).setVisible(currentMode!=Mode.POPULAR);
	    menu.findItem(R.id.upcoming).setVisible(currentMode!=Mode.UPCOMING);
	    menu.findItem(R.id.top).setVisible(currentMode!=Mode.TOP);
	    menu.findItem(R.id.hot).setVisible(currentMode!=Mode.HOT);
	    return true;
	 }
	
	  public boolean onOptionsItemSelected(MenuItem item) {  
		  int id = item.getItemId();
		  switch(id) {
		  case R.id.popular: currentMode=Mode.POPULAR; break;
		  case R.id.upcoming: currentMode=Mode.UPCOMING; break;
		  case R.id.top: currentMode=Mode.TOP; break;
		  case R.id.hot: currentMode=Mode.HOT; break;
		  }
		  Log.i(TAG, "Loading "+getString(currentMode.nameid));
		  loadData();
		  return true;
	  }
	  
	  private Handler removeAdapter = new Handler() {
	        public void handleMessage(Message msg) {
	        	setListAdapter(null);
	        }
	    };
	  private Handler handler = new Handler() {
	        public void handleMessage(Message msg) {
	        	setListAdapter((ListAdapter)msg.obj);
	        	String newTitle = getIntent().getExtras().getString("display")+" - "+getString(currentMode.nameid);
	        	Log.d(TAG,"New title: "+newTitle);
	        	setTitle(newTitle);
				
	        }
	    };
	    
	    Handler refreshHandler = new Handler() {
	    	public void handleMessage(Message msg) {
	    		getListView().invalidateViews();
	    	}
	    };
	
	void loadData() { loadData(null); }
	    
	void loadData(final List<JSONObject> list) {
		new Thread(){public void run() {
		try {
			removeAdapter.sendMessage(new Message());
			Message m = new Message();
			m.obj = new DiggStoriesListAdapter(ListStories.this,"stories/"+getIntent().getExtras().getString("path")+"/"+currentMode.pathAppend,"stories","title", refreshHandler,list);
			handler.sendMessage(m);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		}}.start();
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putInt("currentMode", currentMode.ordinal());
	}
	
	@Override
	public Object onRetainNonConfigurationInstance() {
	    final List<JSONObject> list = ((DiggStoriesListAdapter)getListView().getAdapter()).getList();
	    return list;
	}

	
	/** Called when the activity is first created. */
    @SuppressWarnings("unchecked")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); // Loads the comment from resources
        if(savedInstanceState!=null) { // If saved instance state
        	currentMode = Mode.values()[savedInstanceState.getInt("currentMode")];
        }
        
        final Object data = getLastNonConfigurationInstance();
        if(data==null) {
        	//No preloaded, just load normally.
        	loadData();
        } else {
        	loadData((List<JSONObject>) data); // Passed from previous self.
        }
    }
    
    protected void  onListItemClick  (final ListView l, View v, int position, long id)  {
    	JSONObject j = null;
    	try {
    		j = (JSONObject) l.getAdapter().getItem(position);
    	} catch(IndexOutOfBoundsException e) {
    		new Thread() { public void run() {
    		// Load more items.
    		DiggStoriesListAdapter adapter = (DiggStoriesListAdapter) l.getAdapter();
    		try {
				adapter.loadMore(refreshHandler);
			} catch (ClientProtocolException e1) {
				reportError(e1);
			} catch (URISyntaxException e1) {
				reportError(e1);
			} catch (IOException e1) {
				reportError(e1);
			} catch (JSONException e1) {
				reportError(e1);
			}
    		} }.start();
    		return;
    	}
    	Intent i = new Intent(this,ViewStory.class);
    	try {
			i.putExtra("id", j.getInt("id"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
    	startActivity(i);
    }
}
